<?php

namespace app\index\controller;

use app\index\model\Banner as BannerModel;
use app\index\model\Category as CategoryModel;
use app\index\model\Goods as GoodsModel;
use app\index\model\Links as LinksModel;
use app\index\model\Nav as NavModel;
use think\Db;
use think\Log;

class Index extends Common
{
    /**
     * @Notes:
     * @User:    this邹
     * @CreateDate:  2019/2/21 0021 11:36
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        // 热搜词
        $webtag = config('web.WEB_TAG');
        $TagList = explode(',', $webtag);
        $this->assign('TagList', $TagList);

        $linksModel = new LinksModel();
        // 获取友情链接信息
        $LinksList = $linksModel->findLinksList();
        $this->assign('LinksList', $LinksList);

        $navModel = new NavModel();
        // 获取导航栏信息
        $NavList = $navModel->findNavList();
        $this->assign('NavList', $NavList);

        $categoryModel = new CategoryModel();
        // 获取产品分类信息
        $CategoryList = $categoryModel->findCategoryList();
        $this->assign('CategoryList', $CategoryList);
    }


    /**
     * @Notes:   首页产品列表(需要)
     * @User:    this邹
     * @CreateDate:  2019/2/21 0021 11:36
     * @return array|mixed|\think\response\View
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $bannerModel = new BannerModel();
        // 获取Banner信息
        $BannerList = $bannerModel->findBannerList();
        $this->assign('BannerList', $BannerList);

        $goodsModel = new GoodsModel();
        // 获取产品信息
        $goodsList = $goodsModel->findGoodsList();
        $this->assign('GoodsList', $goodsList['goodsList']);
        return view();
    }

    /**
     * @Notes:   分类搜索产品列表（需要）
     * @User:    this邹
     * @CreateDate:  2019/2/21 0021 11:35
     * @return array|mixed|\think\response\View|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cat()
    {
        $id = input('id');
        $this->assign('cid', $id);
        $sort = input('sort');
        $sort = empty($sort) ? preg_replace('# #', '', config('web.WEB_SORT')) : $sort;
        $this->assign('sort', $sort);

        if (empty($id)) {
            Log::write('缺少参数，分类ID不能为空', 'info');
            return $this->error('亲！你迷路了');
        } else {

            $categoryModel = new CategoryModel();
            // 查找指定产品分类ID信息
            $Category = $categoryModel->findCategoryById($id);
            $this->assign('Category', $Category);
            if ($Category) {
                $goodsModel = new GoodsModel();
                // 根据产品分类ID查找所有产品
                $goodsList = $goodsModel->findGoodsList('', $id, $sort, '');
                $this->assign('GoodsList', $goodsList['goodsList']);
                return view();
            } else {
                Log::write('缺少参数，没有这个分类信息', 'info');
                $this->error("亲！你迷路了！");
            }
        }
    }

    /**
     * @Notes:   九块九(卷后价格小于10元)
     * @User:    this邹
     * @CreateDate:  2019/2/21 0021 17:21
     * @return array|mixed|\think\response\View
     * @throws \think\exception\DbException
     */
    public function nine()
    {
        $goodsModel = new GoodsModel();
        // 根据卷后价格小于10元、查找所有产品
        $goodsList = $goodsModel->findGoodsList('', '', '', 10);
        $this->assign('GoodsList', $goodsList['goodsList']);
        $this->assign('nav_curr', 'nine');
        return view();
    }

    /**
     * @Notes:   20元封顶(卷后价格小于等于20元)
     * @User:    this邹
     * @return array|mixed|\think\response\View
     * @throws \think\exception\DbException
     */
    public function twenty()
    {
        $goodsModel = new GoodsModel();
        // 根据卷后价格小于10元、查找所有产品
        $goodsList = $goodsModel->findGoodsList('', '', '', 20);
        $this->assign('GoodsList', $goodsList['goodsList']);
        $this->assign('nav_curr', 'twenty');
        return view();
    }

    /**
     * @Notes:   爆款疯抢
     * @User:    this邹
     * @return array|mixed|\think\response\View
     * @throws \think\exception\DbException
     */
    public function hot()
    {
        $goodsModel = new GoodsModel();
        //根据月销量500、查找所有产品
        $goodsList = $goodsModel->findGoodsList('', '', '', '', '', 500);
        $this->assign('GoodsList', $goodsList['goodsList']);
        $this->assign('nav_curr', 'hot');
        return view();
    }


    /**
     * 根据产品主键ID查找产品详情
     * @return array|mixed|\think\response\View|void
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function goodsItem()
    {
        $goodsId = input('id');
        if (empty($goodsId)) {
            Log::write('缺少参数，产品ID不能为空', 'info');
            return $this->error('亲！你迷路了');
        } else {
            $goodsModel = new GoodsModel();
            // 检测产品是否存在
            $isTrueGoods = $goodsModel->isTrueGoodsById($goodsId);
            if ($isTrueGoods) {

                //写入浏览记录cookie
                $person_dtl_history = cookie('person_dtl_history');
                if (!$person_dtl_history || !in_array($goodsId, $person_dtl_history)) {
                    $person_dtl_history[] = $goodsId;
                }
                cookie('person_dtl_history', $person_dtl_history);

                // 产品浏览量+1
                $goodsModel->increaseView($goodsId);

                // 获取产品信息
                $goodsItem = $goodsModel->getGoodsById($goodsId);
                $this->assign('Goods', $goodsItem);

                //取同产品类目数据
                $categoryId = $goodsItem['cid'];
                $goodsList = $goodsModel->findGoodsList('', $categoryId, '', '');
                $this->assign('GoodsList', $goodsList['goodsList']);

                return view();
            } else {
                Log::write('缺少参数，没有此产品ID数据', 'info');
                return $this->error('亲！你迷路了');
            }
        }
    }

    /**
     * 超级搜索出来的产品   根据产品numIid查找产品详情
     * @return array|mixed|\think\response\View|void
     */
    public function goodsItemNumIid()
    {
        $numIid = input('id');
        if (empty($numIid)) {
            Log::write('缺少参数，产品numIid不能为空', 'info');
            return $this->error('亲！你迷路了');
        } else {
            $goodsModel = new GoodsModel();
            // 检测产品是否存在
            $isTrueGoods = $goodsModel->isTrueGoodsByNumIid($numIid);
            if ($isTrueGoods) {

                // 获取产品信息
                $goodsItem = $goodsModel->getGoodsByNumIid($numIid);
                $this->assign('Goods', $goodsItem);

                $goodsId = $goodsItem['id'];
                $categoryId = $goodsItem['cid'];

                //写入浏览记录cookie
                $person_dtl_history = cookie('person_dtl_history');
                if (!$person_dtl_history || !in_array($goodsId, $person_dtl_history)) {
                    $person_dtl_history[] = $goodsId;
                }
                cookie('person_dtl_history', $person_dtl_history);

                // 产品浏览量+1
                $goodsModel->increaseView($goodsId);

                //取同产品类目数据
                $goodsList = $goodsModel->findGoodsList('', $categoryId, '', '');
                $this->assign('GoodsList', $goodsList['goodsList']);

                return view();
            } else {
                Log::write('缺少参数，没有此产品numIid数据', 'info');
                return $this->error('亲！你迷路了');
            }
        }
    }

    /**
     * 超级搜索列表渲染页面（需要）
     * @return array|mixed|\think\response\View|void
     * @throws \think\exception\DbException
     */
    public function search()
    {
        $ks = input('ks');
        $this->assign('ks', $ks);

        if (empty($ks)) {
            Log::write('缺少参数，搜索关键字不能为空', 'info');
            return $this->error('亲！你迷路了');
        } else {

            // 1.先查找本地产品
            $GoodsDb = new GoodsModel();
            $goodsList = $GoodsDb->findGoodsList($ks);
            $goodsList = $goodsList['goodsList'];
            $this->assign('GoodsList', $goodsList);
            $this->assign('paging_flag', true);

            // 2.本地产品未找到则进行淘宝搜索
            if (empty($goodsList[0])) {
                $ajaxRequest = new AjaxRequest();
                $goodsList = $ajaxRequest->superSearch($ks, "40", "1", "total_sales");
                $this->assign('GoodsList', $goodsList['item_list']);
                $this->assign('paging_flag', false);
            }
            return view();
        }
    }

    /**
     * 当前浏览器浏览记录
     * @return array|mixed|\think\response\View
     * @throws \think\exception\DbException
     */
    public function history()
    {
        $historyGoodsId = cookie('person_dtl_history');
        if ($historyGoodsId) {
            $GoodsDb = new GoodsModel();
            $goodsList = $GoodsDb->findGoodsList('', '', '', '', $historyGoodsId);
        } else {
            $goodsList = [];
        }
        $this->assign('GoodsList', $goodsList['goodsList']);
        $this->assign('nav_curr', 'history');
        return view();
    }

    // todo  这个不需要不知道干嘛的
    //采集程序
    private function collect_unit($keyword, $cid)
    {
        vendor('taobao.TopClient');
        vendor('taobao.ResultSet');
        vendor('taobao.RequestCheckUtil');
        vendor('taobao.TopLogger');
        vendor('taobao.request.TbkDgItemCouponGetRequest');
        $c = new \TopClient();
        $c->appkey = config('web.WEB_TBKEY');//淘宝KEY
        $c->secretKey = config('web.WEB_TBSECREC');//淘宝SECREC
        $req = new \TbkDgItemCouponGetRequest;
        $req->setAdzoneId(get_adzoneid(config('web.WEB_YHQPID')));//高拥PID
        $req->setPlatform("1");
        //$req->setCat($info['cid']);
        $req->setPageSize("20");
        $req->setQ($keyword);
        $req->setPageNo("1");
        $resp = $c->execute($req);
        $resp = object_to_array($resp);
        if (isset($resp['code'])) {
            return $this->error('采集器接口错误：' . $resp['msg']);
        }
        if (!isset($resp['results'])) {
            return $this->error('采集器接口错');
        }
        $result_data = $resp['results']['tbk_coupon'];
        $result_data = array_slice($result_data, 0, 20);//取100条
        $item = $items = [];
        foreach ($result_data as $k => $v) {
            if (false) {
                /*continue;*/
            } else {
                $item['cid'] = $cid;//分类
                if (session('userid')) {
                    $item['uid'] = session('userid');//发布者ID
                } else {
                    $item['uid'] = '1';//发布者ID
                }
                $item['title'] = $v['title'];//标题
                $item['pic'] = str_replace('https', 'http', $v['pict_url']);//图片
                $item['view'] = 1;//浏览量
                $item['numIid'] = $v['num_iid'];//商品ID
                $item['price'] = $v['zk_final_price'];//原价
                $item['couponPrice'] = $item['price'] - get_word($v['coupon_info'], '减', '元');//现价
                $item['couponRate'] = round(($item['couponPrice'] / $item['price']) * 10, 1);//折扣
                $item['commissionRate'] = $v['commission_rate'];//佣金率  
                $item['commission'] = round($item['price'] * ($item['commissionRate'] / 100), 1);//佣金  
                $item['volume'] = $v['volume'];//30天销量
                $item['nick'] = $v['nick'];//掌柜旺旺名
                $item['sellerId'] = $v['seller_id'];//卖家id
                $item['clickUrl'] = $v['coupon_click_url'];//推广链接
                $item['taoToken'] = '';//淘口令
                $item['couponAmount'] = get_word($v['coupon_info'], '减', '元');//优惠卷
                $item['couponTotalcount'] = $v['coupon_total_count'];//优惠券总量
                $item['couponRemaincount'] = $v['coupon_remain_count'];//优惠券剩余量
                if ($v['user_type'] == 1) {
                    $item['userType'] = "0";
                } else {
                    $item['userType'] = "1";
                }
                $item['dxjhType'] = "0";//定向计划
                $item['startTime'] = time();//开始时间
                $item['endTime'] = strtotime($v['coupon_end_time'] . "+1 day");//结束时间
                $item['keywords'] = implode(',', get_tags($item['title']));//关键词
                if ($v['item_description']) {
                    $item['description'] = $v['item_description'];//描述
                } else {
                    $item['description'] = $item['title'] . '，现价只需要' . $item['price'] . '元，领券后下单还可优惠' . $item['couponAmount'] . '元，赶紧抢购吧！';//描述
                }
                $item['content'] = '';//内容
            }
            $GoodsDb = Db::name('goods');
            $query = $GoodsDb->where('numIid', '=', $item['numIid'])->select();
            if (!$query) {
                $items[] = $item;
            } else {
                $GoodsDb->where('numIid', $item['numIid'])->update($item);
            }
        }
        if (!empty($items)) {
            $result = $GoodsDb->insertAll($items);
        }
    }
}